/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import { AstTreeUtils, ts, ArkMethod, ArkFile, ArkAssignStmt, Type, FieldSignature } from "arkanalyzer/lib";
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { BaseChecker, BaseMetaData } from "../BaseChecker";
import { Defects, IssueReport } from '../../model/Defects';
import { ClassMatcher, FileMatcher, MatcherCallback, MatcherTypes, MethodMatcher } from "../../matcher/Matchers";
import { Utils } from '../../Index';
import { Rule } from "../../model/Rule";
import { RuleListUtil } from "../../utils/common/DefectsList";
import { RuleFix } from '../../model/Fix';
interface Position {
    line: number;
    character: number;
}
interface OptionObject {
    conditionalAssign?: boolean,
    returnAssign?: boolean,
    nestedBinaryExpressions?: boolean,
    ternaryOperandBinaryExpressions?: boolean,
    ignoreJSX?: 'none' | 'all' | 'multi-line' | 'single-line',
    enforceForArrowConditionals?: boolean,
    enforceForSequenceExpressions?: boolean,
    enforceForNewInMemberExpressions?: boolean,
    enforceForFunctionPrototypeMethods?: boolean,
    allowParensAfterCommentPattern?: 'any-string-pattern' | '@type'
}
type OptionKey = 'all' | 'functions';
type OptionsTuple = [OptionKey?, OptionObject?];
const defaultOptions: OptionsTuple = [
    'all',
    {
        conditionalAssign: true,
        returnAssign: true,
        nestedBinaryExpressions: true,
        ternaryOperandBinaryExpressions: true,
        ignoreJSX: 'none',
        enforceForArrowConditionals: true,
        enforceForSequenceExpressions: true,
        enforceForNewInMemberExpressions: true,
        enforceForFunctionPrototypeMethods: true,
        allowParensAfterCommentPattern: 'any-string-pattern'
    }
];
const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'NoExtraParensCheck');
const gmetaData: BaseMetaData = {
    severity: 2,
    ruleDocPath: "docs/no-extra-parens-check.md", // TODO: support url
    description: "Unnecessary parentheses around expression."
};
export class NoExtraParensCheck implements BaseChecker {
    readonly metaData: BaseMetaData = gmetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];
    private fileMatcher: FileMatcher = {
        matcherType: MatcherTypes.FILE,
    };
    private classMatcher: ClassMatcher = {
        file: [this.fileMatcher],
        matcherType: MatcherTypes.CLASS
    };
    private methodMatcher: MethodMatcher = {
        matcherType: MatcherTypes.METHOD,
        class: [this.classMatcher]
    };
    public registerMatchers(): MatcherCallback[] {
        const matchBuildCb: MatcherCallback = {
            matcher: this.fileMatcher,
            callback: this.check
        }
        return [matchBuildCb];
    }
    private issueMap: Map<string, IssueReport> = new Map();
    public check = (file: ArkFile) => {
        let options: OptionsTuple;
        if (this.rule && this.rule.option.length > 0) {
            options = this.rule.option as OptionsTuple;
        } else {
            options = defaultOptions;
        }
        this.issueMap.clear();
        const code = file.getCode() ?? '';
        this.checkUnnecessaryParentheses(file, code, options);
        this.reportSortedIssues();
    }
    private checkUnnecessaryParentheses(file: ArkFile, code: string, options: OptionsTuple): Position[] {
        const sourceFile = ts.createSourceFile('temp.ts', code, ts.ScriptTarget.Latest, true);
        const unnecessaryParentheses: Position[] = [];
        if (options[0] === 'all') {
            function extractOutermostObject(node: ts.Node): string | null {
                while (ts.isPropertyAccessExpression(node)) {
                    // 获取属性访问表达式的对象部分
                    node = node.expression;
                }

                // 如果最外层对象是一个标识符，则返回其文本
                if (ts.isIdentifier(node)) {
                    return node.getText();
                }

                // 如果不是标识符，或者无法确定最外层对象，则返回 null
                return null;
            }
            function isAssignmentExpression(node: ts.Node): boolean {
                if(node === undefined){
                    return false;
                }
                // 检查节点是否为二元表达式，并且运算符是否为等号
                return ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken;
            }
            function isWithinFunctionOrArrowFunction(node: ts.Node): boolean {
                if(node === undefined){
                    return false;
                }
                // 递归地向上遍历 AST，直到找到顶层节点或函数/箭头函数节点
                while (node && !(ts.isFunctionDeclaration(node) || ts.isArrowFunction(node))) {
                    node = node.parent;
                }
                return ts.isFunctionDeclaration(node) || ts.isArrowFunction(node);
            }
            function isWithinReturnOrArrowFunction(node: ts.Node): boolean {
                if(node === undefined){
                    return false;
                }
                // 递归地向上遍历 AST，直到找到顶层节点或返回语句/箭头函数节点
                while (node && !(ts.isReturnStatement(node) || ts.isArrowFunction(node))) {
                    node = node.parent;
                }
                return ts.isReturnStatement(node) || ts.isArrowFunction(node);
            }
            function findFunctionExpression(node: ts.Node): ts.FunctionExpression | null {
                if (ts.isFunctionExpression(node)) {
                    return node;
                }
                for (const child of node.getChildren()) {
                    const result = findFunctionExpression(child);
                    if (result !== null) {
                        return result;
                    }
                }
                return null;
            }
            function findRegExpExpression(node: ts.Node): boolean {
                if(node === undefined){
                    return false;
                }
                const text = node.getText();
                const typeAssertionCommentRegex = /\/\*\*\s*@type\s*{\s*[^}]*\s*}\s*\*\//;
                if (typeAssertionCommentRegex.test(text)) {
                    // 如果括号内包含类型断言注释，则认为括号是不必要的
                    return true;
                }
                for (const child of node.getChildren()) {
                    if (findRegExpExpression(child)) {
                        return true;
                    }
                }
                return false;
            }
            function isSimpleExpression(node: ts.Node): boolean {
                if (options[1]) {
                    // 如果节点是括号表达式
                    if (ts.isParenthesizedExpression(node)) {
                        const parent = node?.parent;
                        const expression = node?.expression;
                        const text = expression?.getText();
                        let flag = true;
                        // 检查箭头函数作为条件表达式的一部分
                        if (ts.isArrowFunction(expression) && ts.isConditionalExpression(parent)) {
                            return false; 
                        }
                        if (ts.isAsExpression(expression) && ts.isConditionalExpression(parent)) {
                            if(options[1].nestedBinaryExpressions !== undefined){
                                if (options[1].nestedBinaryExpressions == false) {
                                    return false;
                                }else{
                                    return true;
                                }
                            }else{
                                return true;
                            }
                        }
                        if (ts.isAsExpression(expression)) {
                            // 如果父节点是二元运算符或条件表达式，并且括号不是用来改变运算优先级的，则认为括号是不必要的
                            if ((ts.isBinaryExpression(parent) && ![
                                ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken, ts.SyntaxKind.AsteriskToken, ts.SyntaxKind.SlashToken,
                                ts.SyntaxKind.PercentToken, ts.SyntaxKind.LessThanToken, ts.SyntaxKind.LessThanEqualsToken,
                                ts.SyntaxKind.GreaterThanToken, ts.SyntaxKind.GreaterThanEqualsToken, ts.SyntaxKind.EqualsEqualsToken,
                                ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken,
                                ts.SyntaxKind.CaretToken
                            ].includes(parent.operatorToken?.kind)) || ts.isConditionalExpression(parent)) {
                                return true;
                            }
                            return false;
                        }
                        // 检查类型断言表达式
                        if (ts.isTypeAssertionExpression(expression) && ts.isConditionalExpression(parent)) {
                            if(options[1].nestedBinaryExpressions !== undefined){
                                if (options[1].nestedBinaryExpressions == false) {
                                    return false;
                                }else{
                                    return true;
                                }
                            }else{
                                return true;
                            }
                        }
                        if (findFunctionExpression(node)) {
                            if (ts.isConditionalExpression(parent)) {
                                return false;
                            }
                            if (options[1].enforceForFunctionPrototypeMethods !== undefined) {
                                if (options[1].enforceForFunctionPrototypeMethods == false) {
                                    return false;
                                } else {
                                    return true;
                                }
                            } else {
                                return true;
                            }
                        }
                        // 新增对逗号表达式的检查
                        if (text.includes(',')) {
                            // 检查父节点是否为 ForOfStatement
                            if (ts.isForOfStatement(parent)) {
                                return false;
                            }
                        }
                        ts.forEachChild(expression, child => {
                            if (ts.isPropertyAccessExpression(child)) {
                                const outermostObject = extractOutermostObject(child);
                                if (outermostObject) {
                                    flag = true;
                                } else {
                                    flag = false;
                                }
                            }
                        });
                        if (!flag) {
                            return false;
                        }
                        if (ts.isBinaryExpression(expression) && expression.operatorToken?.kind === ts.SyntaxKind.EqualsToken) {
                            if (ts.isWhileStatement(parent) || ts.isIfStatement(parent) || ts.isForStatement(parent) || ts.isDoStatement(parent) || ts.isSwitchStatement(parent)) {
                                if (options[1].conditionalAssign !== undefined) {
                                    if (options[1].conditionalAssign == true) {
                                        return true;
                                    } else {
                                        return false;
                                    }
                                }
                                else {
                                    return true;
                                }
                            }
                        }
                        if (ts.isParenthesizedExpression(node)) {
                            const expression = node?.expression;
                            if (isAssignmentExpression(expression)) {
                                const parent = node?.parent;
                                if (isWithinReturnOrArrowFunction(parent)) {
                                    if (isWithinFunctionOrArrowFunction(parent)) {
                                        if (options[1].returnAssign !== undefined) {
                                            if (options[1].returnAssign == false) {
                                                return false;
                                            } else {
                                                return true;
                                            }
                                        }
                                        else {
                                            return true;
                                        }
                                    }
                                }
                            }
                        }
                        if (ts.isBinaryExpression(parent)) {
                            const operator = parent?.operatorToken?.kind;
                            if ([ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken].includes(operator)) {
                                if (options[1].nestedBinaryExpressions !== undefined) {
                                    if (options[1].nestedBinaryExpressions == false) {
                                        return false;
                                    } else {
                                        return true;
                                    }
                                }
                                else {
                                    return true;
                                }
                            }
                            if ([ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken, ts.SyntaxKind.AsteriskToken, ts.SyntaxKind.SlashToken, ts.SyntaxKind.PercentToken].includes(operator)) {
                                if (options[1].nestedBinaryExpressions !== undefined) {
                                    if (options[1].nestedBinaryExpressions == false) {
                                        return false;
                                    } else {
                                        return true;
                                    }
                                }
                                else {
                                    return true;
                                }
                            }
                        }
                        if (ts.isConditionalExpression(parent)) {
                            // 获取三元运算符的条件、真值和假值部分
                            const condition = parent?.condition;
                            const whenTrue = parent?.whenTrue;
                            const whenFalse = parent?.whenFalse;
                            const isConditionParenthesized = ts.isParenthesizedExpression(condition as ts.Node);
                            const isWhenTrueParenthesized = ts.isParenthesizedExpression(whenTrue as ts.Node);
                            const isWhenFalseParenthesized = ts.isParenthesizedExpression(whenFalse as ts.Node);
                            // 如果三元运算符的任何操作数被单独括号包围，则返回false（表示这些括号不是多余的）
                            if (isConditionParenthesized || isWhenTrueParenthesized || isWhenFalseParenthesized) {
                                if (options[1].ternaryOperandBinaryExpressions !== undefined) {
                                    if (options[1].ternaryOperandBinaryExpressions == false) {
                                        return false;
                                    } else {
                                        return true;
                                    }
                                } else {
                                    return true;
                                }
                            }
                        }
                        if (ts.isArrowFunction(parent)) {
                            const body = parent?.body;
                            if (ts.isParenthesizedExpression(body)) {
                                const expression = body?.expression;
                                const text = expression?.getText();
                                if (ts.isConditionalExpression(expression)) {
                                    if (options[1].enforceForArrowConditionals !== undefined) {
                                        if (options[1].enforceForArrowConditionals == false) {
                                            return false;
                                        } else {
                                            return true;
                                        }
                                    } else {
                                        return true;
                                    }
                                }
                            }
                        }
                        if (ts.isBinaryExpression(expression) && expression?.operatorToken?.kind === ts.SyntaxKind.CommaToken) {
                            if (ts.isParenthesizedExpression(expression.parent as ts.Node)) {
                                if (options[1].enforceForSequenceExpressions !== undefined) {
                                    if (options[1].enforceForSequenceExpressions == false) {
                                        return false;
                                    } else {
                                        return true;
                                    }
                                } else {
                                    return true;
                                }
                            }
                        }
                        if (ts.isParenthesizedExpression(node) && ts.isNewExpression(node.expression)) {
                            if (options[1].enforceForNewInMemberExpressions !== undefined) {
                                if (options[1].enforceForNewInMemberExpressions == false) {
                                    return false;
                                } else {
                                    return true;
                                }
                            } else {
                                return true;
                            }
                        }
                        if (findRegExpExpression(parent)) {
                            if (options[1].allowParensAfterCommentPattern !== undefined) {
                                if (options[1].allowParensAfterCommentPattern == '@type') {
                                    return false;
                                } else {
                                    return true;
                                }
                            } else {
                                return true;
                            }
                        }
                        // 检查括号内是否为方法调用，并且该方法调用本身不需要括号
                        if (ts.isCallExpression(expression) && !ts.isParenthesizedExpression(expression)) {
                            // 如果父节点不是需要改变运算优先级的节点，则认为是不必要的括号
                            if (!(ts.isBinaryExpression(parent) && [
                                ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken, ts.SyntaxKind.AsteriskToken, ts.SyntaxKind.SlashToken,
                                ts.SyntaxKind.PercentToken, ts.SyntaxKind.LessThanToken, ts.SyntaxKind.LessThanEqualsToken,
                                ts.SyntaxKind.GreaterThanToken, ts.SyntaxKind.GreaterThanEqualsToken, ts.SyntaxKind.EqualsEqualsToken,
                                ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken,
                                ts.SyntaxKind.CaretToken
                            ].includes(parent?.operatorToken?.kind)) &&
                                !(ts.isConditionalExpression(parent))
                            ) {
                                return true;
                            }
                        }
                        if (ts.isPropertyAccessExpression(parent) || ts.isCallExpression(parent)) {
                            return false;
                        }
                    }
                }
                return ts.isIdentifier(node) ||
                    ts.isLiteralExpression(node) ||
                    (ts.isBinaryExpression(node) && isSimpleExpression(node.left) && isSimpleExpression(node.right)) ||
                    (ts.isPrefixUnaryExpression(node) && isSimpleExpression(node.operand)) ||
                    (ts.isPostfixUnaryExpression(node) && isSimpleExpression(node.operand)) ||
                    (ts.isParenthesizedExpression(node) && isSimpleExpression(node.expression));
            }

            const traverse = (node: ts.Node): void => {
                if (ts.isParenthesizedExpression(node)) {
                    const innerExpression = node?.expression;
                    const parent = innerExpression?.parent!;
                    // 判断括号内的表达式是否为简单表达式，并且括号不是用来改变运算优先级的
                    if (isSimpleExpression(node) &&
                        !(ts.isBinaryExpression(parent) && [
                            ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken, ts.SyntaxKind.AsteriskToken, ts.SyntaxKind.SlashToken,
                            ts.SyntaxKind.PercentToken, ts.SyntaxKind.LessThanToken, ts.SyntaxKind.LessThanEqualsToken,
                            ts.SyntaxKind.GreaterThanToken, ts.SyntaxKind.GreaterThanEqualsToken, ts.SyntaxKind.EqualsEqualsToken,
                            ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken,
                            ts.SyntaxKind.CaretToken
                        ].includes(parent?.operatorToken?.kind))) {
                        const startPosition = node?.getStart();
                        let defect: Defects;
                        const expression = node?.expression;
                        const fixText = expression?.getText();
                        const positionInfo = sourceFile?.getLineAndCharacterOfPosition(startPosition);
                        const pos = node?.getStart();
                        const end = node?.getEnd();
                        unnecessaryParentheses.push({ line: positionInfo.line + 1, character: positionInfo.character + 1 });
                        for (const unnecessaryParenthese of unnecessaryParentheses) {
                            const fixKey = unnecessaryParenthese.line + '%' + unnecessaryParenthese.character + '%' + this.rule.ruleId;
                            const existingDefect = this.issueMap.get(fixKey);
                            if (!existingDefect) {
                                defect = this.addIssueReport(file, unnecessaryParenthese);
                                let fix: RuleFix = this.ruleFix(pos, end, fixText);
                                this.issueMap.set(defect.fixKey, { defect, fix });
                            }
                        }
                    }
                }
                ts.forEachChild(node, childNode => traverse(childNode));
            }
            traverse(sourceFile);
        }
        else if (options[0] == 'functions') {
            function findFunctionExpression(node: ts.Node): ts.FunctionExpression | null {
                if (ts.isFunctionExpression(node)) {
                    return node;
                }
                for (const child of node?.getChildren()) {
                    const result = findFunctionExpression(child);
                    if (result !== null) {
                        return result;
                    }
                }
                return null;
            }
            function isUnnecessaryFunctionParentheses(node: ts.Node): boolean {
                if (ts.isParenthesizedExpression(node)) {
                    const expression = node?.expression;
                    const parent = expression?.parent;
                    const functionExpr = findFunctionExpression(expression);
                    if (functionExpr !== null) {
                        if (findFunctionExpression(node) && ts.isParenthesizedExpression(node) && ts.isParenthesizedExpression(expression)) {
                            return false; // 如果函数表达式被括号包围并作为调用表达式的参数，则不认为是多余的
                        }
                        if (ts.isBinaryExpression(parent)) {
                            if (parent.left === functionExpr || parent.right === functionExpr) {
                                return false;
                            }
                        }
                        if (ts.isConditionalExpression(parent)) {
                            if (parent.condition === functionExpr || parent.whenTrue === functionExpr || parent.whenFalse === functionExpr) {
                                return false;
                            }
                        }
                        if (ts.isConditionalExpression(expression) &&
                            ts.isFunctionExpression(expression.condition) &&
                            expression.condition === functionExpr) {
                            if (ts.isParenthesizedExpression(parent)) {
                                return false;
                            }
                        }

                        return true;
                    }
                }
                return false;
            }
            const traverse = (node: ts.Node, sourceFile: ts.SourceFile, unnecessaryParentheses: { line: number; character: number }[]): void => {
                if (ts.isParenthesizedExpression(node)) {
                    if (isUnnecessaryFunctionParentheses(node)) {
                        const startPosition = node?.getStart();
                        let defect: Defects;
                        const expression = node?.expression;
                        const fixText = expression?.getText();
                        const positionInfo = sourceFile?.getLineAndCharacterOfPosition(startPosition);
                        const pos = node?.getStart();
                        const end = node?.getEnd();
                        unnecessaryParentheses.push({ line: positionInfo.line + 1, character: positionInfo.character + 1 });
                        for (const unnecessaryParenthese of unnecessaryParentheses) {
                            const fixKey = unnecessaryParenthese.line + '%' + unnecessaryParenthese.character + '%' + this.rule.ruleId;
                            const existingDefect = this.issueMap.get(fixKey);
                            if (!existingDefect) {
                                defect = this.addIssueReport(file, unnecessaryParenthese);
                                let fix: RuleFix = this.ruleFix(pos, end, fixText);
                                this.issueMap.set(defect.fixKey, { defect, fix });
                            }
                        }
                    }
                }
                ts.forEachChild(node, childNode => traverse(childNode, sourceFile, unnecessaryParentheses));
            }
            traverse(sourceFile, sourceFile, unnecessaryParentheses);
        } else {
            let option = options[0] as unknown as OptionObject;
            function extractOutermostObject(node: ts.Node): string | null {
                while (ts.isPropertyAccessExpression(node)) {
                    // 获取属性访问表达式的对象部分
                    node = node?.expression;
                }

                // 如果最外层对象是一个标识符，则返回其文本
                if (ts.isIdentifier(node)) {
                    return node?.getText();
                }

                // 如果不是标识符，或者无法确定最外层对象，则返回 null
                return null;
            }
            function isAssignmentExpression(node: ts.Node): boolean {
                // 检查节点是否为二元表达式，并且运算符是否为等号
                return ts.isBinaryExpression(node) && node?.operatorToken?.kind === ts.SyntaxKind.EqualsToken;
            }
            function isWithinFunctionOrArrowFunction(node: ts.Node): boolean {
                // 递归地向上遍历 AST，直到找到顶层节点或函数/箭头函数节点
                while (node && !(ts.isFunctionDeclaration(node) || ts.isArrowFunction(node))) {
                    node = node?.parent;
                }
                return ts.isFunctionDeclaration(node) || ts.isArrowFunction(node);
            }
            function isWithinReturnOrArrowFunction(node: ts.Node): boolean {
                // 递归地向上遍历 AST，直到找到顶层节点或返回语句/箭头函数节点
                while (node && !(ts.isReturnStatement(node) || ts.isArrowFunction(node))) {
                    node = node?.parent;
                }
                return ts.isReturnStatement(node) || ts.isArrowFunction(node);
            }
            function findFunctionExpression(node: ts.Node): ts.FunctionExpression | null {
                if (ts.isFunctionExpression(node)) {
                    return node;
                }
                for (const child of node.getChildren()) {
                    const result = findFunctionExpression(child);
                    if (result !== null) {
                        return result;
                    }
                }
                return null;
            }
            function findRegExpExpression(node: ts.Node): boolean {
                const text = node?.getText();
                const typeAssertionCommentRegex = /\/\*\*\s*@type\s*{\s*[^}]*\s*}\s*\*\//;
                if (typeAssertionCommentRegex.test(text)) {
                    // 如果括号内包含类型断言注释，则认为括号是不必要的
                    return true;
                }
                for (const child of node.getChildren()) {
                    if (findRegExpExpression(child)) {
                        return true;
                    }
                }
                return false;
            }
            function isSimpleExpression(node: ts.Node): boolean {
                if (option)
                    // 如果节点是括号表达式
                    if (ts.isParenthesizedExpression(node)) {
                        const parent = node?.parent;
                        const expression = node?.expression;
                        const text = expression?.getText();
                        let flag = true;
                        // 检查箭头函数作为条件表达式的一部分
                        if (ts.isArrowFunction(expression) && ts.isConditionalExpression(parent)) {
                            return false; 
                        }
                        if (ts.isAsExpression(expression) && ts.isConditionalExpression(parent)) {
                            if(option.nestedBinaryExpressions !== undefined){
                                if (option.nestedBinaryExpressions == false) {
                                    return false;
                                }else{
                                    return true;
                                }
                            }else{
                                return true;
                            }
                        }
                        if (ts.isAsExpression(expression)) {
                            // 如果父节点是二元运算符或条件表达式，并且括号不是用来改变运算优先级的，则认为括号是不必要的
                            if ((ts.isBinaryExpression(parent) && ![
                                ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken, ts.SyntaxKind.AsteriskToken, ts.SyntaxKind.SlashToken,
                                ts.SyntaxKind.PercentToken, ts.SyntaxKind.LessThanToken, ts.SyntaxKind.LessThanEqualsToken,
                                ts.SyntaxKind.GreaterThanToken, ts.SyntaxKind.GreaterThanEqualsToken, ts.SyntaxKind.EqualsEqualsToken,
                                ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken,
                                ts.SyntaxKind.CaretToken
                            ].includes(parent.operatorToken?.kind)) || ts.isConditionalExpression(parent)) {
                                return true;
                            }
                            return false;
                        }
                        // 检查类型断言表达式
                        if (ts.isTypeAssertionExpression(expression) && ts.isConditionalExpression(parent)) {
                            if(option.nestedBinaryExpressions !== undefined){
                                if (option.nestedBinaryExpressions == false) {
                                    return false;
                                }else{
                                    return true;
                                }
                            }else{
                                return true;
                            }
                        }
                        if (findFunctionExpression(node)) {
                            const text = node?.getText();
                            if (ts.isConditionalExpression(parent)) {
                                return false;
                            }
                            if (option.enforceForFunctionPrototypeMethods !== undefined) {
                                if (option.enforceForFunctionPrototypeMethods == false) {
                                    return false;
                                } else {
                                    return true;
                                }
                            } else {
                                return true;
                            }
                        }
                        // 新增对逗号表达式的检查
                        if (text.includes(',')) {
                            // 检查父节点是否为 ForOfStatement
                            if (ts.isForOfStatement(parent)) {
                                return false;
                            }
                        }
                        ts.forEachChild(expression, child => {
                            const childText = child.getText();
                            if (ts.isPropertyAccessExpression(child)) {
                                const outermostObject = extractOutermostObject(child);
                                if (outermostObject) {
                                    flag = true;
                                } else {
                                    flag = false;
                                }
                            }
                        });
                        if (!flag) {
                            return false;
                        }
                        if (ts.isBinaryExpression(expression) && expression?.operatorToken?.kind === ts.SyntaxKind.EqualsToken) {
                            if (ts.isWhileStatement(parent) || ts.isIfStatement(parent) || ts.isForStatement(parent) || ts.isDoStatement(parent) || ts.isSwitchStatement(parent)) {
                                if (option.conditionalAssign !== undefined) {
                                    if (option.conditionalAssign == true) {
                                        return true;
                                    } else {
                                        return false;
                                    }
                                }
                                else {
                                    return true;
                                }
                            }
                        }
                        if (ts.isParenthesizedExpression(node)) {
                            const expression = node?.expression;
                            if (isAssignmentExpression(expression)) {
                                const parent = node?.parent;
                                if (isWithinReturnOrArrowFunction(parent)) {
                                    if (isWithinFunctionOrArrowFunction(parent)) {
                                        if (option.returnAssign !== undefined) {
                                            if (option.returnAssign == false) {
                                                return false;
                                            } else {
                                                return true;
                                            }
                                        }
                                        else {
                                            return true;
                                        }
                                    }
                                }
                            }
                        }
                        if (ts.isBinaryExpression(parent)) {
                            const operator = parent?.operatorToken?.kind;
                            if ([ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken].includes(operator)) {
                                if (option.nestedBinaryExpressions !== undefined) {
                                    if (option.nestedBinaryExpressions == false) {
                                        return false;
                                    } else {
                                        return true;
                                    }
                                }
                                else {
                                    return true;
                                }
                            }
                            if ([ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken, ts.SyntaxKind.AsteriskToken, ts.SyntaxKind.SlashToken, ts.SyntaxKind.PercentToken].includes(operator)) {
                                if (option.nestedBinaryExpressions !== undefined) {
                                    if (option.nestedBinaryExpressions == false) {
                                        return false;
                                    } else {
                                        return true;
                                    }
                                }
                                else {
                                    return true;
                                }
                            }
                        }
                        if (ts.isConditionalExpression(parent)) {
                            // 获取三元运算符的条件、真值和假值部分
                            const condition = parent?.condition;
                            const whenTrue = parent?.whenTrue;
                            const whenFalse = parent?.whenFalse;
                            const isConditionParenthesized = ts.isParenthesizedExpression(condition as ts.Node);
                            const isWhenTrueParenthesized = ts.isParenthesizedExpression(whenTrue as ts.Node);
                            const isWhenFalseParenthesized = ts.isParenthesizedExpression(whenFalse as ts.Node);
                            // 如果三元运算符的任何操作数被单独括号包围，则返回false（表示这些括号不是多余的）
                            if (isConditionParenthesized || isWhenTrueParenthesized || isWhenFalseParenthesized) {
                                if (option.ternaryOperandBinaryExpressions !== undefined) {
                                    if (option.ternaryOperandBinaryExpressions == false) {
                                        return false;
                                    } else {
                                        return true;
                                    }
                                } else {
                                    return true;
                                }
                            }
                        }
                        if (ts.isArrowFunction(parent)) {
                            const body = parent?.body;
                            if (ts.isParenthesizedExpression(body)) {
                                const expression = body?.expression;
                                if (ts.isConditionalExpression(expression)) {
                                    if (option.enforceForArrowConditionals !== undefined) {
                                        if (option.enforceForArrowConditionals == false) {
                                            return false;
                                        } else {
                                            return true;
                                        }
                                    } else {
                                        return true;
                                    }
                                }
                            }
                        }
                        if (ts.isBinaryExpression(expression) && expression?.operatorToken?.kind === ts.SyntaxKind.CommaToken) {
                            if (ts.isParenthesizedExpression(expression.parent as ts.Node)) {
                                if (option.enforceForSequenceExpressions !== undefined) {
                                    if (option.enforceForSequenceExpressions == false) {
                                        return false;
                                    } else {
                                        return true;
                                    }
                                } else {
                                    return true;
                                }
                            }
                        }
                        if (ts.isParenthesizedExpression(node) && ts.isNewExpression(node.expression)) {
                            if (option.enforceForNewInMemberExpressions !== undefined) {
                                if (option.enforceForNewInMemberExpressions == false) {
                                    return false;
                                } else {
                                    return true;
                                }
                            } else {
                                return true;
                            }
                        }
                        if (findRegExpExpression(parent)) {
                            if (option.allowParensAfterCommentPattern !== undefined) {
                                if (option.allowParensAfterCommentPattern == '@type') {
                                    return false;
                                } else {
                                    return true;
                                }
                            } else {
                                return true;
                            }
                        }
                        // 检查括号内是否为方法调用，并且该方法调用本身不需要括号
                        if (ts.isCallExpression(expression) && !ts.isParenthesizedExpression(expression)) {
                            // 如果父节点不是需要改变运算优先级的节点，则认为是不必要的括号
                            if (!(ts.isBinaryExpression(parent) && [
                                ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken, ts.SyntaxKind.AsteriskToken, ts.SyntaxKind.SlashToken,
                                ts.SyntaxKind.PercentToken, ts.SyntaxKind.LessThanToken, ts.SyntaxKind.LessThanEqualsToken,
                                ts.SyntaxKind.GreaterThanToken, ts.SyntaxKind.GreaterThanEqualsToken, ts.SyntaxKind.EqualsEqualsToken,
                                ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken,
                                ts.SyntaxKind.CaretToken
                            ].includes(parent?.operatorToken?.kind)) &&
                                !(ts.isConditionalExpression(parent))
                            ) {
                                return true;
                            }
                        }
                        if (ts.isPropertyAccessExpression(parent) || ts.isCallExpression(parent)) {
                            return false;
                        }
                    }
                return ts.isIdentifier(node) ||
                    ts.isLiteralExpression(node) ||
                    (ts.isBinaryExpression(node) && isSimpleExpression(node.left) && isSimpleExpression(node.right)) ||
                    (ts.isPrefixUnaryExpression(node) && isSimpleExpression(node.operand)) ||
                    (ts.isPostfixUnaryExpression(node) && isSimpleExpression(node.operand)) ||
                    (ts.isParenthesizedExpression(node) && isSimpleExpression(node.expression));
            }

            const traverse = (node: ts.Node): void => {
                if (ts.isParenthesizedExpression(node)) {
                    const innerExpression = node?.expression;
                    const parent = innerExpression?.parent!;
                    // 判断括号内的表达式是否为简单表达式，并且括号不是用来改变运算优先级的
                    if (isSimpleExpression(node) &&
                        !(ts.isBinaryExpression(parent) && [
                            ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken, ts.SyntaxKind.AsteriskToken, ts.SyntaxKind.SlashToken,
                            ts.SyntaxKind.PercentToken, ts.SyntaxKind.LessThanToken, ts.SyntaxKind.LessThanEqualsToken,
                            ts.SyntaxKind.GreaterThanToken, ts.SyntaxKind.GreaterThanEqualsToken, ts.SyntaxKind.EqualsEqualsToken,
                            ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken,
                            ts.SyntaxKind.CaretToken
                        ].includes(parent?.operatorToken?.kind))) {
                        const startPosition = node?.getStart();
                        let defect: Defects;
                        const expression = node?.expression;
                        const fixText = expression?.getText();
                        const positionInfo = sourceFile?.getLineAndCharacterOfPosition(startPosition);
                        const pos = node?.getStart();
                        const end = node?.getEnd();
                        unnecessaryParentheses.push({ line: positionInfo.line + 1, character: positionInfo.character + 1 });
                        for (const unnecessaryParenthese of unnecessaryParentheses) {
                            const fixKey = unnecessaryParenthese.line + '%' + unnecessaryParenthese.character + '%' + this.rule.ruleId;
                            const existingDefect = this.issueMap.get(fixKey);
                            if (!existingDefect) {
                                defect = this.addIssueReport(file, unnecessaryParenthese);
                                let fix: RuleFix = this.ruleFix(pos, end, fixText);
                                this.issueMap.set(defect.fixKey, { defect, fix });
                            }
                        }
                    }
                }
                ts.forEachChild(node, childNode => traverse(childNode));
            }
            traverse(sourceFile);
        }
        return unnecessaryParentheses;
    }
    private ruleFix(pos: number, end: number, fixText: string): RuleFix {
        return { range: [pos, end], text: fixText };
    }
    private reportSortedIssues(): void {
        if (this.issueMap.size === 0) {
            return;
        }

        const sortedIssues = Array.from(this.issueMap.entries())
            .sort(([keyA], [keyB]) => Utils.sortByLineAndColumn(keyA, keyB));

        this.issues = [];

        sortedIssues.forEach(([_, issue]) => {
            RuleListUtil.push(issue.defect);
            this.issues.push(issue);
        });
    }

    private addIssueReport(arkFile: ArkFile, lineAndColumn: Position): Defects {
        const severity = this.rule.alert ?? this.metaData.severity;
        const warnInfo = this.getLineAndColumn(arkFile, lineAndColumn);
        this.metaData.description = this.metaData.description.padEnd(130);
        const fixKey = warnInfo.line + '%' + warnInfo.startCol + '%' + this.rule.ruleId;
        const mergeKey = warnInfo.filePath + '%' + fixKey + '%' + this.metaData.description + this.rule.ruleId;
        const defect = new Defects(warnInfo.line, warnInfo.startCol, this.metaData.description, severity, this.rule.ruleId,
            mergeKey, this.metaData.ruleDocPath, true, false, false, fixKey);
        this.defects.push(defect);

        return defect;
    }
    private getLineAndColumn(arkfile: ArkFile, lineColumn: Position) {
        if (arkfile) {
            const originPath = arkfile.getFilePath();
            return { line: lineColumn.line, startCol: lineColumn.character, filePath: originPath };
        } else {
            logger.debug('arkFile is null');
        }
        return { line: -1, startCol: -1, endCol: -1, filePath: '' };
    }
}